library(tidyverse)  # ggplot(), %>%, mutate(), and friends 
library(broom)
library(MatchIt)  # Match things
library(Rcpp)
library(MASS)
library(modelsummary)
library(IRdisplay)
library(haven)
library(dplyr)
library(ggpubr)





map <- read_csv('dataset76_20.csv')
map <- filter(map, Year2 > 1990)

regions <- read_csv('C:/./states_region.csv')
regions <- dplyr::rename(regions, State=state_x)


# replace string for being identical acrsso map and nibrs regions
map$State[map$State == 'Rhodes Island'] <- 'Rhode Island'
map$State[map$State == 'District of Columbia'] <- 'District Of Columbia'
# adding missing states
regions <- regions %>% add_row(...1= 888, State = "Alaska", country_region = "west", country_division="Pacific")
regions <- regions %>% add_row(...1= 999, State = "California", country_region = "west", country_division="Pacific")
regions <- regions %>% add_row(...1= 45878, State = "Florida", country_region = "south", country_division="South Atlantic")
regions <- regions %>% add_row(...1= 97666, State = "New Jersey", country_region = "north east", country_division="Middle Atlantic")


# add region and division to map dataset
map<- merge(map, regions, by="State")

nibrs <- readRDS('C:/./nibrs_prepared_dataset_91_20.rds')
nibrs <- dplyr::rename(nibrs, State=state.x)
map_count <- map %>% count(State) # count map state frequencies
nibrs_count <- nibrs %>% count(State)

# final cleaning
map <- subset(map, map$Agentype != 4)
map <- subset(map, map$State != "PAPSP8")
nibrs$agency_indicator[nibrs$agency_indicator == '5'] <- "other agencies"




both_count <- merge(map_count, nibrs_count, by="State", all.x=TRUE)

#install.packages('usmap')
library(usmap)
library(ggplot2)

both_count <- dplyr::rename(both_count, state=State)

###### avg_solved per dataset (per race)

solved_race_map <- map %>%
  group_by(State, VicRace_Black) %>%
  summarise_at(vars(Solved_Yes), list(name = mean))

solved_race_map <- spread(solved_race_map, key=VicRace_Black, value=name)


solved_race_nibrs <- nibrs %>%
  group_by(State, race_of_victim_black) %>%
  summarise_at(vars(Solved), list(name=mean))

solved_race_nibrs <- spread(solved_race_nibrs, key=race_of_victim_black, value=name)

both_solved_race <- merge(solved_race_map, solved_race_nibrs, by="State", all.x=TRUE)
#rename for easier plotting
both_solved_race <- dplyr::rename(both_solved_race, state=State)
both_solved_race <- dplyr::rename(both_solved_race, map_noblack='0.x')
both_solved_race <- dplyr::rename(both_solved_race, map_black='1.x')
both_solved_race <- dplyr::rename(both_solved_race, nibrs_noblack='0.y')
both_solved_race <- dplyr::rename(both_solved_race, nibrs_black='1.y')


########## MAPS PLOTTING

# map data - COUNT
plot_map_count <- plot_usmap(data = both_count, values = "n.x", color = "black") + 
  scale_fill_continuous(
    low = "white", high = "blue", name = "MAP: Homicide Victims", label = scales::comma
  ) + theme(legend.position = "left", legend.key.size = unit(0.5, 'cm'), legend.key.width= unit(0.5, 'cm'), legend.text = element_text(size = 12), 
            legend.title = element_text(size = 14))

# nibrs data - COUNT
plot_nibrs_count <- plot_usmap(data = both_count, values = "n.y", color = "black") + 
  scale_fill_continuous(
    low = "white", high = "blue", name = "NIBRS: Homicide Victims", label = scales::comma,
    breaks = c(0, 2500, 5000, 7500, 10000, 12500)) + 
  theme(legend.position = "right",legend.key.size = unit(0.5, 'cm'), legend.key.width= unit(0.5, 'cm'), legend.text = element_text(size = 12), 
        legend.title = element_text(size = 14))

# map data - avg solved NOT BLACK
plot_map_solved_notblack <- plot_usmap(data = both_solved_race, values = "map_noblack", color = "black") + 
  scale_fill_continuous(
    type = 'viridis', name = "MAP: Ratio Solved (Non-Black)", label = function(x) ifelse(x < 1, sprintf(".%02d", x*100), scales::comma(x)), 
    limits = c(0, 1)
  ) + theme(legend.position = "right", legend.key.size = unit(0.5, 'cm'), legend.key.width = unit(0.5, 'cm'),legend.text = element_text(size = 12), 
            legend.title = element_text(size = 14))

# map data - avg solved BLACK
plot_map_solved_black <- plot_usmap(data = both_solved_race, values = "map_black", color = "black") + 
  scale_fill_continuous(
    type='viridis', name = "MAP: Ratio Solved (Black)", label = function(x) ifelse(x < 1, sprintf(".%02d", x*100), scales::comma(x)), 
    limits = c(0, 1)
  ) + theme(legend.position = "right", legend.key.size = unit(0.5, 'cm'), legend.key.width = unit(0.5, 'cm'),legend.text = element_text(size = 12), 
            legend.title = element_text(size = 14))


# nibrs data - avg solved NOT BLACK
plot_nibrs_solved_notblack <- plot_usmap(data = both_solved_race, values = "nibrs_noblack", color = "black") + 
  scale_fill_continuous(
    type='viridis', name = "NIBRS: Ratio Solved (Non-Black)", label = function(x) ifelse(x < 1, sprintf(".%02d", x*100), scales::comma(x)), 
    limits = c(0, 1)
  ) + theme(legend.position = "right", legend.key.size = unit(0.5, 'cm'), legend.key.width = unit(0.5, 'cm'),legend.text = element_text(size = 12), 
            legend.title = element_text(size = 14))


# nibrs data - avg solved BLACK
plot_nibrs_solved_black <- plot_usmap(data = both_solved_race, values = "nibrs_black", color = "black") + 
  scale_fill_continuous(
    type='viridis', name = "NIBRS: Ratio Solved (Black)", label = function(x) ifelse(x < 1, sprintf(".%02d", x*100), scales::comma(x)), 
    limits = c(0, 1)
  ) + theme(legend.position = "right", legend.key.size = unit(0.5, 'cm'), legend.key.width = unit(0.5, 'cm'),legend.text = element_text(size = 12), 
            legend.title = element_text(size = 14))



ggarrange(plot_map_count,  plot_nibrs_count,  plot_map_solved_black, plot_nibrs_solved_black,  plot_map_solved_notblack,  plot_nibrs_solved_notblack,
          labels = c("A", "B", "C", "D", "E", "F"),
          ncol = 2, nrow = 3, align="v", common.legend= FALSE,
          legend="left")

# create yearly count data for the two datasets
nibrs  <- dplyr::rename(nibrs, Year2=year.x)
map_year <- map %>%
  count(Year2)

nibrs_year <- nibrs %>%
  count(Year2)

both_years <- merge(map_year, nibrs_year, by="Year2", all.x=TRUE)




# create average solved for the two datasets
mean_solved_map <- map %>%                                        # Specify data frame
  group_by(Year2) %>%                         # Specify group indicator
  summarise_at(vars(Solved_Yes),              # Specify column
               list(name = mean))               # Specify function


nibrs  <- dplyr::rename(nibrs, Solved_Yes=Solved) # change var name in nibrs for future merge


mean_solved_nibrs <- nibrs %>%                                        # Specify data frame
  group_by(Year2) %>%                         # Specify group indicator
  summarise_at(vars(Solved_Yes),              # Specify column
               list(name = mean))    

both_avg_solved <- merge(mean_solved_map, mean_solved_nibrs, by="Year2", all.x=TRUE)


###### avg_solved per dataset (per race)

solved_race_map <- map %>%
  group_by(State, VicRace_Black) %>%
  summarise_at(vars(Solved_Yes), list(name = mean))

solved_race_map <- spread(solved_race_map, key=VicRace_Black, value=name)


solved_race_nibrs <- nibrs %>%
  group_by(State, race_of_victim_black) %>%
  summarise_at(vars(Solved_Yes), list(name=mean))

solved_race_nibrs <- spread(solved_race_nibrs, key=race_of_victim_black, value=name)

both_solved_race <- merge(solved_race_map, solved_race_nibrs, by="State", all.x=TRUE)


# plotting
library(reshape)
#melting for easier plotting
melt_both_year <- melt(both_years, id=c("Year2"))
melt_both_avg <-  melt(both_avg_solved, id=c("Year2"))


# plotting
count_plot <- ggplot(melt_both_year, aes(Year2, value, color = variable), size = 5) + geom_line(size=1.5)+
  labs(x='Year', y='N of Homicide Victims')+
  scale_color_manual(labels = c("MAP", "NIBRS"), values = c("blue3", "lightsalmon"))+
  labs(linetype = "Data Source", color = "Data Source")+
  #geom_vline(xintercept=melt_both_year$Year2[melt_both_year$value == max(melt_both_year$value)],color='red')+
  theme_bw() + theme(axis.text=element_text(size=15),
                     axis.title=element_text(size=17), legend.title=element_text(size=15), 
                     legend.text=element_text(size=15))



solv_plot <- ggplot(melt_both_avg, aes(Year2, value, color = variable), size = 5) + geom_line(size=1.5)+
  labs(x='Year', y='Ratio Solved')+
  ylim(0,1)+
  scale_color_manual(labels = c("MAP", "NIBRS"), values = c("blue3", "lightsalmon"))+
  labs(linetype = "Data Source", color = "Data Source")+
  theme_bw() + theme(axis.text=element_text(size=15),
                     axis.title=element_text(size=17), legend.title=element_text(size=15), 
                     legend.text=element_text(size=15))+
  scale_y_continuous(breaks = c(0, 0.2, 0.4, 0.6, 0.8, 1), labels = function(x) {
    ifelse(x == 0, "0", 
           ifelse(x > 0, gsub("^0", "", format(x, nsmall = 2)), 
                  gsub("^-0", "-.", gsub("^-0\\.", "-.", format(x, nsmall = 2)))
           )
    )
  })+
  coord_cartesian(ylim = c(0, 1))


ggarrange(count_plot, solv_plot, 
          labels = c("A", "B"),
          ncol = 1, nrow = 2, align="v", common.legend= TRUE,
          legend="bottom")



### create dataset for plotting bar chart of average solved

mean_solved_map <- data.frame(matrix(ncol = 3, nrow = 0))
x <- c("dataset", "type", "avg_solved")
colnames(mean_solved_map) <- x


#change type
mean_solved_map$dataset <- as.character((mean_solved_map$dataset))
mean_solved_map$type <- as.character((mean_solved_map$type))
mean_solved_map$avg_solved<- as.numeric((mean_solved_map$avg_solved))

# add rows (black avg. solved map (1976-2020))
mean_solved_map<- dplyr::add_row(
  mean_solved_map,
  dataset='MAP (1991-2020)',
  type='Black',
  avg_solved=mean(map$Solved_Yes[map$VicRace_Black == 1 & !is.na(map$Solved_Yes)], na.rm = TRUE))

# add rows (non black avg. solved map (1976-2020))

mean_solved_map<- dplyr::add_row(
  mean_solved_map,
  dataset = 'MAP (1991-2020)',
  type = 'Non Black',
  avg_solved = mean(map$Solved_Yes[map$VicRace_Black == 0 & !is.na(map$Solved_Yes)], na.rm = TRUE))

# add rows (overall avg. solved map (1976-2020))
mean_solved_map<- dplyr::add_row(
  mean_solved_map,
  dataset='MAP (1991-2020)',
  type='Overall',
  avg_solved=mean(map$Solved_Yes))


# add rows (black avg. nibrs)
mean_solved_map<- dplyr::add_row(
  mean_solved_map,
  dataset='NIBRS (1991-2020)',
  type='Black',
  avg_solved=mean(nibrs[nibrs$race_of_victim_black == 1, 'Solved_Yes']))

# add rows (non-black avg. nibrs)
mean_solved_map<- dplyr::add_row(
  mean_solved_map,
  dataset='NIBRS (1991-2020)',
  type='Non Black',
  avg_solved=mean(nibrs[nibrs$race_of_victim_black == 0, 'Solved_Yes']))

# add rows (overall avg. solved nibrs (1991-2020))
mean_solved_map<- dplyr::add_row(
  mean_solved_map,
  dataset='NIBRS (1991-2020)',
  type='Overall',
  avg_solved=mean(nibrs$Solved_Yes))

# plot as bar chart
bar_chart <- ggplot(mean_solved_map, aes(fill = type, y = avg_solved, x = dataset)) + 
  geom_bar(position = "dodge", stat = "identity", na.rm = TRUE) +
  coord_flip(ylim = c(0, 1)) +
  labs(y = 'Ratio Solved', x = 'Dataset') +
  guides(fill = guide_legend(title = "Victim\'s Race")) +
  scale_fill_manual(values = c("deepskyblue4", "darkturquoise", "darkslategray2")) +
  scale_y_continuous(labels = function(x) {
    ifelse(x < 1, sub("^0", "", format(x, nsmall = 2)), format(x, nsmall = 2))
  }) +
  theme_bw()

bar_chart <- bar_chart + theme(axis.text=element_text(size=15),
                               axis.title=element_text(size=17), legend.title=element_text(size=15), 
                               legend.text=element_text(size=15))

ggarrange(ggarrange(count_plot, solv_plot, 
                    labels = c("A", "B"),
                    ncol = 2, nrow = 1, align="v", common.legend= TRUE,
                    legend="bottom"), bar_chart, labels=c("","C"), nrow=2)


################################################## SUMMARY STATISTICS

############### MAP


###### VIC COUNT

# MAP
viccount_map <- map %>% group_by(VicCount, VicRace_Black) %>% summarise(Count = n(),
                                                                        Percentage=n()/nrow(.), 
                                                                        Mean = mean(Solved_Yes))
viccount_map_w <- reshape(as.data.frame(viccount_map), idvar="VicCount", 
                          v.names=c("Count", "Percentage", "Mean"),
                          timevar="VicRace_Black",
                          direction="wide")

xtable(viccount_map_w)

viccount_map_long <- viccount_map %>%  pivot_longer(cols=c('Mean', 'Percentage'), names_to="Type", values_to='ratios')

viccount_map_plot <- ggplot(viccount_map_long)+
  geom_point(viccount_map_long, mapping=aes(y=VicCount, x=ratios, shape=Type, color=as.factor(VicRace_Black)),size=4, alpha=0.8)+
  theme_bw()+ylab("N of Victims (Same Event)")+xlab("Ratio")+scale_color_manual(values=c("royalblue1", "indianred3"), labels=c("Not Black", "Black"))+
  scale_shape_manual(values=c(4,3), labels=c("Ratio of Solved", "Ratio of Cases"))+labs(shape="Type of Ratio", colour="Victim's Race")+
  xlim(0,1)+theme(axis.text=element_text(size=12),
                  axis.title=element_text(size=16))+scale_y_continuous(breaks = scales::pretty_breaks(n = 22))+
  theme(plot.margin = margin(1,0.5,0,0.5, "cm"))  +
  scale_x_continuous(labels = function(x) {
    ifelse(x == 0, "0", 
           ifelse(x > 0, gsub("^0", "", format(x, nsmall = 2)), 
                  gsub("^-0", "-.", gsub("^-0\\.", "-.", format(x, nsmall = 2)))
           )
    )
  })



# NIBRS
viccount_nibrs <- nibrs %>% group_by(total_victims, race_of_victim_black) %>% summarise(Count = n(),
                                                                                        Percentage=n()/nrow(.), 
                                                                                        Mean = mean(Solved_Yes))

xtable(viccount_nibrs)

viccount_nibrs_long <- viccount_nibrs %>% pivot_longer(cols=c('Mean', 'Percentage'), names_to="Type", values_to="ratios")


viccount_nibrs_plot <- ggplot(viccount_nibrs_long)+
  geom_point(viccount_nibrs_long, mapping=aes(y=total_victims, x=ratios, shape=Type, color=as.factor(race_of_victim_black)),size=4, alpha=1)+
  theme_bw()+ylab("N of Victims (Same Event)")+xlab("Ratio")+scale_color_manual(values=c("royalblue1", "indianred3"), labels=c("Not Black", "Black"))+
  scale_shape_manual(values=c(4,3), labels=c("Ratio of Solved", "Ratio of Cases"))+labs(shape="Type of Ratio", colour="Victim's Race")+
  scale_y_discrete(labels=c("Female", "Male", "Unknown"))+
  xlim(0,1)+theme(axis.text=element_text(size=12),
                  axis.title=element_text(size=16))+scale_y_continuous(breaks = scales::pretty_breaks(n = 30))+
  theme(plot.margin = margin(1,0.5,0,0.5, "cm")) +
  scale_x_continuous(labels = function(x) {
    ifelse(x == 0, "0", 
           ifelse(x > 0, gsub("^0", "", format(x, nsmall = 2)), 
                  gsub("^-0", "-.", gsub("^-0\\.", "-.", format(x, nsmall = 2)))
           )
    )
  })



# combine
ggarrange(viccount_map_plot, viccount_nibrs_plot, common.legend = TRUE, legend="bottom", labels=c("MAP","NIBRS"))


######## OFF COUNT

## MAP
offcount_map <- map %>% group_by(OffCount, VicRace_Black) %>% summarise(Count = n(),
                                                                        Percentage=n()/nrow(.), 
                                                                        Mean = mean(Solved_Yes))

xtable(offcount_map)

offcount_map_long <- offcount_map %>%  pivot_longer(cols=c('Mean', 'Percentage'), names_to="Type", values_to='ratios')

offcount_map_plot <- ggplot(offcount_map_long)+
  geom_point(offcount_map_long, mapping=aes(y=OffCount, x=ratios, shape=Type, color=as.factor(VicRace_Black)),size=4, alpha=0.8)+
  theme_bw()+ylab("N of Offenders (Same Event)")+xlab("Ratio")+scale_color_manual(values=c("royalblue1", "indianred3"), labels=c("Not Black", "Black"))+
  scale_shape_manual(values=c(4,3), labels=c("Ratio of Solved", "Ratio of Cases"))+labs(shape="Type of Ratio", colour="Victim's Race")+
  xlim(0,1)+ylim(0,41)+theme(axis.text=element_text(size=12),
                             axis.title=element_text(size=16)) +scale_y_continuous(n.breaks=30)+
  theme(plot.margin = margin(1,0.5,0,0.5, "cm"))+scale_y_continuous(breaks = scales::pretty_breaks(n = 30))+
  theme(plot.margin = margin(1,0.5,0,0.5, "cm")) +
  scale_x_continuous(labels = function(x) {
    ifelse(x == 0, "0", 
           ifelse(x > 0, gsub("^0", "", format(x, nsmall = 2)), 
                  gsub("^-0", "-.", gsub("^-0\\.", "-.", format(x, nsmall = 2)))
           )
    )
  })



## NIBRS

offcount_nibrs <- nibrs %>% group_by(total_offender_segments, race_of_victim_black) %>% summarise(Count = n(),
                                                                                                  Percentage=n()/nrow(.), 
                                                                                                  Mean = mean(Solved_Yes))

xtable(offcount_nibrs)

offcount_nibrs_long <- offcount_nibrs %>% pivot_longer(cols=c('Mean', 'Percentage'), names_to="Type", values_to="ratios")


offcount_nibrs_plot <- ggplot(offcount_nibrs_long)+
  geom_point(offcount_nibrs_long, mapping=aes(y=total_offender_segments, x=ratios, shape=Type, color=as.factor(race_of_victim_black)),size=4, alpha=1)+
  theme_bw()+ylab("N of Offenders (Same Event)")+xlab("Ratio")+scale_color_manual(values=c("royalblue1", "indianred3"), labels=c("Not Black", "Black"))+
  scale_shape_manual(values=c(4,3), labels=c("Ratio of Solved", "Ratio of Cases"))+labs(shape="Type of Ratio", colour="Victim's Race")+
  scale_y_discrete(labels=c("Female", "Male", "Unknown"))+
  xlim(0,1)+theme(axis.text=element_text(size=12),
                  axis.title=element_text(size=16))+scale_y_continuous(breaks = scales::pretty_breaks(n = 30))+
  theme(plot.margin = margin(1,0.5,0,0.5, "cm"))+scale_y_continuous(breaks = scales::pretty_breaks(n = 30))+
  theme(plot.margin = margin(1,0.5,0,0.5, "cm")) +
  scale_x_continuous(labels = function(x) {
    ifelse(x == 0, "0", 
           ifelse(x > 0, gsub("^0", "", format(x, nsmall = 2)), 
                  gsub("^-0", "-.", gsub("^-0\\.", "-.", format(x, nsmall = 2)))
           )
    )
  })


# combine
ggarrange(offcount_map_plot, offcount_nibrs_plot, common.legend = TRUE, legend="bottom", labels=c("MAP", "NIBRS"))


########################## VIC SEX

## MAP

vicsex_map <- map %>% group_by(VicSex, VicRace_Black) %>% summarise(Count = n(),
                                                                    Percentage=n()/nrow(.), 
                                                                    Mean = mean(Solved_Yes))

vicsex_map_w <- reshape(as.data.frame(vicsex_map), idvar="VicSex",
                        v.names=c("Count", "Percentage", "Mean"),
                        timevar="VicRace_Black",
                        direction="wide")

xtable(vicsex_map)

vicsex_map$VicRace_Black <- as.factor(vicsex_map$VicRace_Black)


vicsex_map_long <- vicsex_map %>%  pivot_longer(cols=c('Mean', 'Percentage'), names_to="Type", values_to='ratios')

vicsex_map_plot <- ggplot(vicsex_map_long)+
  geom_point(vicsex_map_long, mapping=aes(y=VicSex, x=ratios, shape=Type, color=VicRace_Black),size=4, alpha=0.8)+
  theme_bw()+ylab("Victim's Sex")+xlab("Ratio")+scale_color_manual(values=c("royalblue1", "indianred3"), labels=c("Not Black", "Black"))+
  scale_shape_manual(values=c(4,3), labels=c("Ratio of Solved", "Ratio of Cases"))+labs(shape="Type of Ratio", colour="Victim's Race")+
  xlim(0,1)+theme(axis.text=element_text(size=12),
                  axis.title=element_text(size=16))+
  scale_x_continuous(labels = function(x) {
    ifelse(x == 0, "0", 
           ifelse(x > 0, gsub("^0", "", format(x, nsmall = 2)), 
                  gsub("^-0", "-.", gsub("^-0\\.", "-.", format(x, nsmall = 2)))
           )
    )
  })+
  coord_cartesian(xlim = c(0, 1))


## NIBRS 



vicsex_nibrs <- nibrs %>% group_by(sex_of_victim, race_of_victim_black) %>% summarise(Count = n(),
                                                                                      Percentage=n()/nrow(.), 
                                                                                      Mean = mean(Solved_Yes))

xtable(vicsex_nibrs)

vicsex_nibrs_long <- vicsex_nibrs %>% pivot_longer(cols=c('Mean', 'Percentage'), names_to="Type", values_to="ratios")


vicsex_nibrs_plot <- ggplot(vicsex_nibrs_long)+
  geom_point(vicsex_nibrs_long, mapping=aes(y=sex_of_victim, x=ratios, shape=Type, color=as.factor(race_of_victim_black)),size=4, alpha=1)+
  theme_bw()+ylab("Victim's Sex")+xlab("Ratio")+scale_color_manual(values=c("royalblue1", "indianred3"), labels=c("Not Black", "Black"))+
  scale_shape_manual(values=c(4,3), labels=c("Ratio of Solved", "Ratio of Cases"))+labs(shape="Type of Ratio", colour="Victim's Race")+
  scale_y_discrete(labels=c("Female", "Male", "Unknown"))+
  xlim(0,1)+theme(axis.text=element_text(size=12),
                  axis.title=element_text(size=16))+
  scale_x_continuous(labels = function(x) {
    ifelse(x == 0, "0", 
           ifelse(x > 0, gsub("^0", "", format(x, nsmall = 2)), 
                  gsub("^-0", "-.", gsub("^-0\\.", "-.", format(x, nsmall = 2)))
           )
    )
  })+
  coord_cartesian(xlim = c(0, 1))



# combine
ggarrange(vicsex_map_plot, vicsex_nibrs_plot, common.legend = TRUE, legend="bottom", labels=c("MAP", "NIBRS"))

##################### AGE CAT


## MAP
agecat_map <- map %>% group_by(AgeCat, VicRace_Black) %>% summarise(Count = n(),
                                                                    Percentage=n()/nrow(.), 
                                                                    Mean = mean(Solved_Yes))

xtable(agecat_map)


agecat_map_long <- agecat_map %>%  pivot_longer(cols=c('Mean', 'Percentage'), names_to="Type", values_to='ratios')

agecat_map_long$AgeCat <- factor(agecat_map_long$AgeCat, levels=c("0-5", "6-10", "11-15", "16-20",
                                                                  "21-25", "26-30", "31-35", "36-40", 
                                                                  "41-45", "46-50", "51-55", "56-60", 
                                                                  "61-65", "66-70", "71-75", "76-80", 
                                                                  "81-85", "86-90", "91-95", "96-99"))

agecat_map_plot <- ggplot(agecat_map_long)+
  geom_point(agecat_map_long, mapping=aes(y=AgeCat, x=ratios, shape=Type, color=as.factor(VicRace_Black)),size=4, alpha=0.8)+
  theme_bw()+ylab("Victim's Age")+xlab("Ratio")+scale_color_manual(values=c("royalblue1", "indianred3"), labels=c("Not Black", "Black"))+
  scale_shape_manual(values=c(4,3), labels=c("Ratio of Solved", "Ratio of Cases"))+labs(shape="Type of Ratio", colour="Victim's Race")+
  xlim(0,1)+theme(axis.text=element_text(size=12),
                  axis.title=element_text(size=16))+
  theme(plot.margin = margin(1,0.5,0,0.5, "cm"))+
  scale_x_continuous(labels = function(x) {
    ifelse(x == 0, "0", 
           ifelse(x > 0, gsub("^0", "", format(x, nsmall = 2)), 
                  gsub("^-0", "-.", gsub("^-0\\.", "-.", format(x, nsmall = 2)))
           )
    )
  })+
  coord_cartesian(xlim = c(0, 1))


# NIBRS
agecat_nibrs <- nibrs %>% group_by(agecat, race_of_victim_black) %>% summarise(Count = n(),
                                                                               Percentage=n()/nrow(.), 
                                                                               Mean = mean(Solved_Yes))

xtable(agecat_nibrs)


agecat_nibrs_long <- agecat_nibrs %>% pivot_longer(cols=c('Mean', 'Percentage'), names_to="Type", values_to="ratios")

agecat_nibrs_long$agecat <- factor(agecat_nibrs_long$agecat, levels=c("0-5", "6-10", "11-15", "16-20",
                                                                      "21-25", "26-30", "31-35", "36-40", 
                                                                      "41-45", "46-50", "51-55", "56-60", 
                                                                      "61-65", "66-70", "71-75", "76-80", 
                                                                      "81-85", "86-90", "91-95", "96-99"))

agecat_nibrs_plot <- ggplot(agecat_nibrs_long)+
  geom_point(agecat_nibrs_long, mapping=aes(y=agecat, x=ratios, shape=Type, color=as.factor(race_of_victim_black)),size=4, alpha=0.8)+
  theme_bw()+ylab("Victim's Age")+xlab("Ratio")+scale_color_manual(values=c("royalblue1", "indianred3"), labels=c("Not Black", "Black"))+
  scale_shape_manual(values=c(4,3), labels=c("Ratio of Solved", "Ratio of Cases"))+labs(shape="Type of Ratio", colour="Victim's Race")+
  xlim(0,1)+theme(axis.text=element_text(size=12),
                  axis.title=element_text(size=16))+
  theme(plot.margin = margin(1,0.5,0,0.5, "cm"))+
  scale_x_continuous(labels = function(x) {
    ifelse(x == 0, "0", 
           ifelse(x > 0, gsub("^0", "", format(x, nsmall = 2)), 
                  gsub("^-0", "-.", gsub("^-0\\.", "-.", format(x, nsmall = 2)))
           )
    )
  })+
  coord_cartesian(xlim = c(0, 1))

# Combine
ggarrange(agecat_map_plot, agecat_nibrs_plot, common.legend = TRUE, legend="bottom", labels=c("MAP", "NIBRS"))

############ DECADE

# MAP

decade_map <- map %>% group_by(Decade, VicRace_Black) %>% summarise(Count = n(),
                                                                    Percentage=n()/nrow(.), 
                                                                    Mean = mean(Solved_Yes))

xtable(decade_map)

decade_map_long <- decade_map %>%  pivot_longer(cols=c('Mean', 'Percentage'), names_to="Type", values_to='ratios')

decade_map_long$Decade <- factor(decade_map_long$Decade, levels=c("90s", "00s", "10s"))

decade_map_plot <- ggplot(decade_map_long)+
  geom_point(decade_map_long, mapping=aes(y=Decade, x=ratios, shape=Type, color=as.factor(VicRace_Black)),size=4, alpha=0.8)+
  theme_bw()+ylab("Decade")+xlab("Ratio")+scale_color_manual(values=c("royalblue1", "indianred3"), labels=c("Not Black", "Black"))+
  scale_shape_manual(values=c(4,3), labels=c("Ratio of Solved", "Ratio of Cases"))+labs(shape="Type of Ratio", colour="Victim's Race")+
  xlim(0,1)+theme(axis.text=element_text(size=12),
                  axis.title=element_text(size=16))+
  scale_x_continuous(labels = function(x) {
    ifelse(x == 0, "0", 
           ifelse(x > 0, gsub("^0", "", format(x, nsmall = 2)), 
                  gsub("^-0", "-.", gsub("^-0\\.", "-.", format(x, nsmall = 2)))
           )
    )
  })+
  coord_cartesian(xlim = c(0, 1))

## NIBRS
decade_nibrs <- nibrs %>% group_by(decade, race_of_victim_black) %>% summarise(Count = n(),
                                                                               Percentage=n()/nrow(.), 
                                                                               Mean = mean(Solved_Yes))

xtable(decade_nibrs)

decade_nibrs_long <- decade_nibrs %>% pivot_longer(cols=c('Mean', 'Percentage'), names_to="Type", values_to="ratios")

decade_nibrs_long$decade <- factor(decade_nibrs_long$decade, levels=c("90s", "00s", "10s"))



decade_nibrs_plot <- ggplot(decade_nibrs_long)+
  geom_point(decade_nibrs_long, mapping=aes(y=decade, x=ratios, shape=Type, color=as.factor(race_of_victim_black)),size=4, alpha=0.8)+
  theme_bw()+ylab("Decade")+xlab("Ratio")+scale_color_manual(values=c("royalblue1", "indianred3"), labels=c("Not Black", "Black"))+
  scale_shape_manual(values=c(4,3), labels=c("Ratio of Solved", "Ratio of Cases"))+labs(shape="Type of Ratio", colour="Victim's Race")+
  xlim(0,1)+theme(axis.text=element_text(size=12),
                  axis.title=element_text(size=16))+
  scale_x_continuous(labels = function(x) {
    ifelse(x == 0, "0", 
           ifelse(x > 0, gsub("^0", "", format(x, nsmall = 2)), 
                  gsub("^-0", "-.", gsub("^-0\\.", "-.", format(x, nsmall = 2)))
           )
    )
  })+
  coord_cartesian(xlim = c(0, 1))

ggarrange(decade_map_plot, decade_nibrs_plot, common.legend = TRUE, legend="bottom", labels=c("MAP", "NIBRS"), hjust=-0.05)


############### WEAPON

### MAP

weapon_map <- map %>% group_by(Weapon, VicRace_Black) %>% summarise(Count = n(),
                                                                    Percentage=n()/nrow(.), 
                                                                    Mean = mean(Solved_Yes))

xtable(weapon_map)


weapon_map_long <- weapon_map %>%  pivot_longer(cols=c('Mean', 'Percentage'), names_to="Type", values_to='ratios')


weapon_map_plot <- ggplot(weapon_map_long)+
  geom_point(weapon_map_long, mapping=aes(y=Weapon, x=ratios, shape=Type, color=as.factor(VicRace_Black)),size=4, alpha=0.8)+
  theme_bw()+ylab("Weapon")+xlab("Ratio")+scale_color_manual(values=c("royalblue1", "indianred3"), labels=c("Not Black", "Black"))+
  scale_shape_manual(values=c(4,3), labels=c("Ratio of Solved", "Ratio of Cases"))+labs(shape="Type of Ratio", colour="Victim's Race")+
  xlim(0,1)+theme(axis.text=element_text(size=12),
                  axis.title=element_text(size=16))+
  scale_x_continuous(labels = function(x) {
    ifelse(x == 0, "0", 
           ifelse(x > 0, gsub("^0", "", format(x, nsmall = 2)), 
                  gsub("^-0", "-.", gsub("^-0\\.", "-.", format(x, nsmall = 2)))
           )
    )
  })+
  coord_cartesian(xlim = c(0, 1))



## NIBRS

weapon_nibrs <- nibrs %>% group_by(weapon, race_of_victim_black) %>% summarise(Count = n(),
                                                                               Percentage=n()/nrow(.), 
                                                                               Mean = mean(Solved_Yes))

xtable(weapon_nibrs)

weapon_nibrs_long <- weapon_nibrs %>% pivot_longer(cols=c('Mean', 'Percentage'), names_to="Type", values_to="ratios")

weapon_nibrs_plot<-ggplot(weapon_nibrs_long)+
  geom_point(weapon_nibrs_long, mapping=aes(y=weapon, x=ratios, shape=Type, color=as.factor(race_of_victim_black)),size=4, alpha=0.8)+
  theme_bw()+ylab("Weapon")+xlab("Ratio")+scale_color_manual(values=c("royalblue1", "indianred3"), labels=c("Not Black", "Black"))+
  scale_shape_manual(values=c(4,3), labels=c("Ratio of Solved", "Ratio of Cases"))+labs(shape="Type of Ratio", colour="Victim's Race")+
  xlim(0,1)+theme(axis.text=element_text(size=12),
                  axis.title=element_text(size=16))+scale_y_discrete(labels=c('Asphyxiation', 'Blunt Object (Club, Hummer,etc.)', 'Drugs/Narcotics/Sleeping Pills',
                                                                              'Explosives', 'Fire/Incendiary Device', 'Firearm (Type not Stated)', 'Handgun', 
                                                                              'Knife/Cutting Instrument', 'Motor Vehicle', 'None', 'Other', 'Other Firearm', 'Personal Weapons',
                                                                              'Poison (Include Gas)', 'Rifle', 'Shotgun', 'Unknown'))+
  scale_x_continuous(labels = function(x) {
    ifelse(x == 0, "0", 
           ifelse(x > 0, gsub("^0", "", format(x, nsmall = 2)), 
                  gsub("^-0", "-.", gsub("^-0\\.", "-.", format(x, nsmall = 2)))
           )
    )
  })+
  coord_cartesian(xlim = c(0, 1))

#combine
ggarrange(weapon_map_plot, weapon_nibrs_plot, common.legend = TRUE, legend="bottom", labels=c("MAP", "NIBRS"))




######## CIRCUMSTANCE

## MAP

circ_map <- map %>% group_by(Circumstance, VicRace_Black) %>% summarise(Count = n(),
                                                                        Percentage=n()/nrow(.), 
                                                                        Mean = mean(Solved_Yes))
xtable(circ_map)

circ_map_long <-circ_map %>%  pivot_longer(cols=c('Mean', 'Percentage'), names_to="Type", values_to='ratios')


circ_map_plot <- ggplot(circ_map_long)+
  geom_point(circ_map_long, mapping=aes(y=Circumstance, x=ratios, shape=Type, color=as.factor(VicRace_Black)),size=4, alpha=0.8)+
  theme_bw()+ylab("Circumstance")+xlab("Ratio")+scale_color_manual(values=c("royalblue1", "indianred3"), labels=c("Not Black", "Black"))+
  scale_shape_manual(values=c(4,3), labels=c("Ratio of Solved", "Ratio of Cases"))+labs(shape="Type of Ratio", colour="Victim's Race")+
  xlim(0,1)+theme(axis.text=element_text(size=12),
                  axis.title=element_text(size=16))+
  scale_x_continuous(labels = function(x) {
    ifelse(x == 0, "0", 
           ifelse(x > 0, gsub("^0", "", format(x, nsmall = 2)), 
                  gsub("^-0", "-.", gsub("^-0\\.", "-.", format(x, nsmall = 2)))
           )
    )
  })+
  coord_cartesian(xlim = c(0, 1))


## NIBRS

circ_nibrs <- nibrs %>% group_by(circumstance, race_of_victim_black) %>% summarise(Count = n(),
                                                                                   Percentage=n()/nrow(.), 
                                                                                   Mean = mean(Solved_Yes))
xtable(circ_nibrs)


circ_nibrs_long <- circ_nibrs %>% pivot_longer(cols=c('Mean', 'Percentage'), names_to="Type", values_to="ratios")



circ_nibrs_plot <- ggplot(circ_nibrs_long)+
  geom_point(circ_nibrs_long, mapping=aes(y=circumstance, x=ratios, shape=Type, color=as.factor(race_of_victim_black)),size=4, alpha=0.8)+
  theme_bw()+ylab("Circumstance")+xlab("Ratio")+scale_color_manual(values=c("royalblue1", "indianred3"), labels=c("Not Black", "Black"))+
  scale_shape_manual(values=c(4,3), labels=c("Ratio of Solved", "Ratio of Cases"))+labs(shape="Type of Ratio", colour="Victim's Race")+
  xlim(0,1)+theme(axis.text=element_text(size=12),
                  axis.title=element_text(size=16))+scale_y_discrete(labels=c('Argument','Assault on LE officer(s)', 'Child playing with weapon',
                                                                              'Criminal killed by police officer', 'Criminal killed by private citizen',
                                                                              'Drug Dealing', 'Gangland', 'Gun-cleaning accident', 'Hunting accident',
                                                                              'Juvenile gang', 'Lovers quarrel', 'Mercy killing', 'Other circumstances',
                                                                              'Other felony involved', 'Other negligent killings', 
                                                                              'Other negligent weapon handling', 'Unknown circumstances'))+
  scale_x_continuous(labels = function(x) {
    ifelse(x == 0, "0", 
           ifelse(x > 0, gsub("^0", "", format(x, nsmall = 2)), 
                  gsub("^-0", "-.", gsub("^-0\\.", "-.", format(x, nsmall = 2)))
           )
    )
  })+
  coord_cartesian(xlim = c(0, 1))


#combine
ggarrange(circ_map_plot, circ_nibrs_plot, common.legend = TRUE, legend="bottom", labels=c("MAP", "NIBRS"))


############## AGENTYPE

## MAP
agent_map <- map %>% group_by(Agentype, VicRace_Black) %>% summarise(Count = n(),
                                                                     Percentage=n()/nrow(.), 
                                                                     Mean = mean(Solved_Yes))
xtable(agent_map)

agent_map_long <-agent_map %>%  pivot_longer(cols=c('Mean', 'Percentage'), names_to="Type", values_to='ratios')


agent_map_plot <- ggplot(agent_map_long)+
  geom_point(agent_map_long, mapping=aes(y=Agentype, x=ratios, shape=Type, color=as.factor(VicRace_Black)),size=4, alpha=0.8)+
  theme_bw()+ylab("Type of Agency")+xlab("Ratio")+scale_color_manual(values=c("royalblue1", "indianred3"), labels=c("Not Black", "Black"))+
  scale_shape_manual(values=c(4,3), labels=c("Ratio of Solved", "Ratio of Cases"))+labs(shape="Type of Ratio", colour="Victim's Race")+
  xlim(0,1)+theme(axis.text=element_text(size=12),
                  axis.title=element_text(size=16))+
  scale_x_continuous(labels = function(x) {
    ifelse(x == 0, "0", 
           ifelse(x > 0, gsub("^0", "", format(x, nsmall = 2)), 
                  gsub("^-0", "-.", gsub("^-0\\.", "-.", format(x, nsmall = 2)))
           )
    )
  })+
  coord_cartesian(xlim = c(0, 1))


## NIBRS

agent_nibrs <- nibrs %>% group_by(agency_indicator, race_of_victim_black) %>% summarise(Count = n(),
                                                                                        Percentage=n()/nrow(.), 
                                                                                        Mean = mean(Solved_Yes))
xtable(agent_nibrs)

agent_nibrs_long <- agent_nibrs %>% pivot_longer(cols=c('Mean', 'Percentage'), names_to="Type", values_to="ratios")



agent_nibrs_plot <- ggplot(agent_nibrs_long)+
  geom_point(agent_nibrs_long, mapping=aes(y=agency_indicator, x=ratios, shape=Type, color=as.factor(race_of_victim_black)),size=4, alpha=0.8)+
  theme_bw()+ylab("Type of Agency")+xlab("Ratio")+scale_color_manual(values=c("royalblue1", "indianred3"), labels=c("Not Black", "Black"))+
  scale_shape_manual(values=c(4,3), labels=c("Ratio of Solved", "Ratio of Cases"))+labs(shape="Type of Ratio", colour="Victim's Race")+
  xlim(0,1)+theme(axis.text=element_text(size=12),
                  axis.title=element_text(size=16))+scale_y_discrete(labels=c('City', 'County', 'Cov. by another agency',
                                                                              'Other agencies', 'State police', 'Tribal', 'University or College'))+
  scale_x_continuous(labels = function(x) {
    ifelse(x == 0, "0", 
           ifelse(x > 0, gsub("^0", "", format(x, nsmall = 2)), 
                  gsub("^-0", "-.", gsub("^-0\\.", "-.", format(x, nsmall = 2)))
           )
    )
  })+
  coord_cartesian(xlim = c(0, 1))



#combine
ggarrange(agent_map_plot, agent_nibrs_plot, common.legend = TRUE, legend="bottom", labels=c("MAP", "NIBRS"), widths=c(0.9,1))


######## MONTHLY AGENCY OVERLAP

### MAP
monthly_agency_overlap_map <-  map %>% group_by(Monthly_Agency_Overlap, VicRace_Black) %>% summarise(Count = n(),
                                                                                                     Percentage=n()/nrow(.), 
                                                                                                     Mean = mean(Solved_Yes))

xtable(monthly_agency_overlap_map)

monthly_agency_overlap_map_long <-monthly_agency_overlap_map %>%  pivot_longer(cols=c('Mean', 'Percentage'), names_to="Type", values_to='ratios')


monthly_agency_overlap_map_plot <- ggplot(monthly_agency_overlap_map_long)+
  geom_point(monthly_agency_overlap_map_long, mapping=aes(y=as.factor(Monthly_Agency_Overlap), x=ratios, shape=Type, color=as.factor(VicRace_Black)),size=4, alpha=0.8)+
  theme_bw()+ylab("Month/Agency Case Overlap")+xlab("Ratio")+scale_color_manual(values=c("royalblue1", "indianred3"), labels=c("Not Black", "Black"))+
  scale_shape_manual(values=c(4,3), labels=c("Ratio of Solved", "Ratio of Cases"))+labs(shape="Type of Ratio", colour="Victim's Race")+
  xlim(0,1)+theme(axis.text=element_text(size=12),
                  axis.title=element_text(size=16))+scale_y_discrete(labels=c('No Case Overlap', 'Case Overlap'))+
  scale_x_continuous(labels = function(x) {
    ifelse(x == 0, "0", 
           ifelse(x > 0, gsub("^0", "", format(x, nsmall = 2)), 
                  gsub("^-0", "-.", gsub("^-0\\.", "-.", format(x, nsmall = 2)))
           )
    )
  })+
  coord_cartesian(xlim = c(0, 1))


### NIBRS

monthly_agency_overlap_nibrs <-  nibrs %>% group_by(Monthly_Agency_Overlap, race_of_victim_black) %>% summarise(Count = n(),
                                                                                                                Percentage=n()/nrow(.), 
                                                                                                                Mean = mean(Solved_Yes))

xtable(monthly_agency_overlap_nibrs)

monthly_agency_overlap_nibrs_long <- monthly_agency_overlap_nibrs %>% pivot_longer(cols=c('Mean', 'Percentage'), names_to="Type", values_to="ratios")



monthly_agency_overlap_nibrs_plot <- ggplot(monthly_agency_overlap_nibrs_long)+
  geom_point(monthly_agency_overlap_nibrs_long, mapping=aes(y=as.factor(Monthly_Agency_Overlap), x=ratios, shape=Type, color=as.factor(race_of_victim_black)),size=4, alpha=0.8)+
  theme_bw()+ylab("Month/Agency Case Overlap")+xlab("Ratio")+scale_color_manual(values=c("royalblue1", "indianred3"), labels=c("Not Black", "Black"))+
  scale_shape_manual(values=c(4,3), labels=c("Ratio of Solved", "Ratio of Cases"))+labs(shape="Type of Ratio", colour="Victim's Race")+
  xlim(0,1)+theme(axis.text=element_text(size=12),
                  axis.title=element_text(size=16))+scale_y_discrete(labels=c('No Case Overlap', 'Case Overlap'))+
  scale_x_continuous(labels = function(x) {
    ifelse(x == 0, "0", 
           ifelse(x > 0, gsub("^0", "", format(x, nsmall = 2)), 
                  gsub("^-0", "-.", gsub("^-0\\.", "-.", format(x, nsmall = 2)))
           )
    )
  })+
  coord_cartesian(xlim = c(0, 1))


#combine
ggarrange(monthly_agency_overlap_map_plot, monthly_agency_overlap_nibrs_plot, common.legend = TRUE, legend="bottom", labels=c("MAP", "NIBRS"))


############ STATE

## MAP
state_map <- map %>% group_by(State, VicRace_Black) %>% summarise(Count = n(),
                                                                  Percentage=n()/nrow(.), 
                                                                  Mean = mean(Solved_Yes))

xtable(state_map)

state_map_long <-state_map %>%  pivot_longer(cols=c('Mean', 'Percentage'), names_to="Type", values_to='ratios')


state_map_plot <- ggplot(state_map_long)+
  geom_point(state_map_long, mapping=aes(y=State, x=ratios, shape=Type, color=as.factor(VicRace_Black)),size=4, alpha=0.8)+
  theme_bw()+ylab("State")+xlab("Ratio")+scale_color_manual(values=c("royalblue1", "indianred3"), labels=c("Not Black", "Black"))+
  scale_shape_manual(values=c(4,3), labels=c("Ratio of Solved", "Ratio of Cases"))+labs(shape="Type of Ratio", colour="Victim's Race")+
  xlim(0,1)+theme(axis.text=element_text(size=12),
                  axis.title=element_text(size=16))+
  scale_x_continuous(labels = function(x) {
    ifelse(x == 0, "0", 
           ifelse(x > 0, gsub("^0", "", format(x, nsmall = 2)), 
                  gsub("^-0", "-.", gsub("^-0\\.", "-.", format(x, nsmall = 2)))
           )
    )
  })+
  coord_cartesian(xlim = c(0, 1))


## NIBRS
state_nibrs <- nibrs %>% group_by(State, race_of_victim_black) %>% summarise(Count = n(),
                                                                             Percentage=n()/nrow(.), 
                                                                             Mean = mean(Solved_Yes))

xtable(state_nibrs)

state_nibrs_long <- state_nibrs %>% pivot_longer(cols=c('Mean', 'Percentage'), names_to="Type", values_to="ratios")



state_nibrs_plot <- ggplot(state_nibrs_long)+
  geom_point(state_nibrs_long, mapping=aes(y=as.factor(State), x=ratios, shape=Type, color=as.factor(race_of_victim_black)),size=4, alpha=0.8)+
  theme_bw()+ylab("State")+xlab("Ratio")+scale_color_manual(values=c("royalblue1", "indianred3"), labels=c("Not Black", "Black"))+
  scale_shape_manual(values=c(4,3), labels=c("Ratio of Solved", "Ratio of Cases"))+labs(shape="Type of Ratio", colour="Victim's Race")+
  xlim(0,1)+theme(axis.text=element_text(size=12),
                  axis.title=element_text(size=16))+
  scale_x_continuous(labels = function(x) {
    ifelse(x == 0, "0", 
           ifelse(x > 0, gsub("^0", "", format(x, nsmall = 2)), 
                  gsub("^-0", "-.", gsub("^-0\\.", "-.", format(x, nsmall = 2)))
           )
    )
  })+
  coord_cartesian(xlim = c(0, 1))



ggarrange(state_map_plot, state_nibrs_plot, common.legend = TRUE, legend="bottom", labels=c("MAP", "NIBRS"))


#### LOCATION TYPE
location_nibrs <- nibrs %>% group_by(location_type, race_of_victim_black) %>% summarise(Count = n(),
                                                                                        Percentage=n()/nrow(.), 
                                                                                        Mean = mean(Solved_Yes))

xtable(location_nibrs)

location_nibrs_long <- location_nibrs %>% pivot_longer(cols=c('Mean', 'Percentage'), names_to="Type", values_to="ratios")



location_nibrs_plot <- ggplot(location_nibrs_long)+
  geom_point(location_nibrs_long, mapping=aes(y=location_type, x=ratios, shape=Type, color=as.factor(race_of_victim_black)),size=4, alpha=0.8)+
  theme_bw()+ylab("Location Type")+xlab("Ratio")+scale_color_manual(values=c("royalblue1", "indianred3"), labels=c("Not Black", "Black"))+
  scale_shape_manual(values=c(4,3), labels=c("Ratio of Solved", "Ratio of Cases"))+labs(shape="Type of Ratio", colour="Victim's Race")+
  xlim(0,1)+theme(axis.text=element_text(size=12),
                  axis.title=element_text(size=16))+
  scale_x_continuous(labels = function(x) {
    ifelse(x == 0, "0", 
           ifelse(x > 0, gsub("^0", "", format(x, nsmall = 2)), 
                  gsub("^-0", "-.", gsub("^-0\\.", "-.", format(x, nsmall = 2)))
           )
    )
  })+
  coord_cartesian(xlim = c(0, 1))


#### POPULATION GROUP
population_nibrs <- nibrs %>% group_by(population_group, race_of_victim_black) %>% summarise(Count = n(),
                                                                                             Percentage=n()/nrow(.), 
                                                                                             Mean = mean(Solved_Yes))

xtable(population_nibrs)

population_nibrs_long <- population_nibrs %>% pivot_longer(cols=c('Mean', 'Percentage'), names_to="Type", values_to="ratios")



population_nibrs_plot <- ggplot(population_nibrs_long)+
  geom_point(population_nibrs_long, mapping=aes(y=population_group, x=ratios, shape=Type, color=as.factor(race_of_victim_black)),size=4, alpha=0.8)+
  theme_bw()+ylab("Population Area")+xlab("Ratio")+scale_color_manual(values=c("royalblue1", "indianred3"), labels=c("Not Black", "Black"))+
  scale_shape_manual(values=c(4,3), labels=c("Ratio of Solved", "Ratio of Cases"))+labs(shape="Type of Ratio", colour="Victim's Race")+
  xlim(0,1)+theme(axis.text=element_text(size=12),
                  axis.title=element_text(size=16))+
  scale_x_continuous(labels = function(x) {
    ifelse(x == 0, "0", 
           ifelse(x > 0, gsub("^0", "", format(x, nsmall = 2)), 
                  gsub("^-0", "-.", gsub("^-0\\.", "-.", format(x, nsmall = 2)))
           )
    )
  })+
  coord_cartesian(xlim = c(0, 1))

